package cn.outsourcing.supermarket.interceptor;

import cn.outsourcing.supermarket.common.Result;
import cn.outsourcing.supermarket.common.constants.CommonConstants;
import cn.outsourcing.supermarket.common.utils.DataUtils;
import cn.outsourcing.supermarket.common.utils.JwtUtils;
import cn.outsourcing.supermarket.mapper.HiolabsUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 后台拦截器
 *
 * @author gzkemays
 * @since 2021/10/26 23:31
 */
@Component
@Slf4j
public class BackstageInterceptor extends HandlerInterceptorAdapter {
  @Resource HiolabsUserMapper userMapper;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    // 忽视 option 跨越请求
    if (!request.getMethod().equals("OPTIONS")) {
      String token = request.getHeader(CommonConstants.TOKEN_HEADER_KEY);
      if (StringUtils.isBlank(token)) {
        DataUtils.writeJson(request, response, Result.builder().errno(400).errmsg("请先登录").build());
        return false;
      }
      if (JwtUtils.settings().build().checkJwt(token) == null) {
        DataUtils.writeJson(request, response, Result.builder().errno(402).errmsg("密钥错误").build());
        return false;
      }
      if (JwtUtils.settings().build().isExpiration(token)) {
        DataUtils.writeJson(request, response, Result.builder().errno(403).errmsg("密钥已过期").build());
        return false;
      }
    }
    return true;
  }
}
